import { deleteCart, getCartList, updateCart } from '@/api/cart'

export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },

  // 修改数据接口
  mutations: {
    setCartList (state, cartList) {
      state.cartList = cartList
    },

    toggleCheck (state, goodsId) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      if (goods) {
        goods.isChecked = !goods.isChecked
      }
    },

    changeAllChecked (state, isChecked) {
      state.cartList.forEach(item => {
        item.isChecked = isChecked
      })
    },

    setCartTotal (state, obj) {
      const { goodsId, cartTotal } = obj
      state.cartList.forEach(item => {
        if (item.goods_id === goodsId) {
          item.goods_num = cartTotal
        }
      })
    }
  },

  // 异步方法
  actions: {
    async getCartList (context) {
      const { data } = await getCartList()
      data.list.forEach(item => {
        item.isChecked = true // 默认选中
      })
      context.commit('setCartList', data.list)
    },

    // 更新购物车物品数量
    async updateCountAction (context, obj) {
      const { goodsNum, goodsId, goodsSkuId } = obj
      const { data: { cartTotal } } = await updateCart(goodsId, goodsNum, goodsSkuId)
      context.commit('setCartTotal', { goodsId, cartTotal })
    },

    // 删除购物车物品
    async deleteCartAction (context) {
      await deleteCart(context.getters.selectCartList.map(item => item.id))
      context.dispatch('getCartList')
    }
  },

  getters: {
    // 求所有商品的累加
    cartTotal (state) {
      return state.cartList.reduce((total, item) => {
        return total + item.goods_num
      }, 0)
    },

    // 选中的商品
    selectCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },

    // 选中的商品总数
    selectTotalCount (state, getters) {
      return getters.selectCartList.reduce((total, item) => {
        return total + item.goods_num
      }, 0)
    },

    // 选中的商品总价
    selectTotalPrice (state, getters) {
      return getters.selectCartList.reduce((total, item) => {
        return total + item.goods_num * item.goods.goods_price_min
      }, 0).toFixed(2)
    },

    // 是否全选
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
